/*
 * @Author: caiqi
 * @Date: 2019-02-14 14:34:34
 * @Last Modified by: cai.qi
 * @Last Modified time: 2020-05-13 18:45:33
 * @Describe:
 */

"use strict";

import { Service } from "egg";

export default class TypeService extends Service {
    // ------------------------------ get
    async get(body: any) {
        const { ctx, app } = this;
        const sequelize = app.Sequelize;
        let _where = {}
        if (body.tag) {
            _where = { tag: body.tag }
        }

        const data = await ctx.model.ModCommodity.findAll({
            where: { status: 1, ..._where },
            order: [['created_at', 'DESC']],
            attributes: [
                'id', 'tag', 'name',
                'introduction', 'introduce', 'price', 'oldprice',
                'specifications',
                'cover', 'collection',
                'created_at', 'folder',
                [sequelize.col('type.id'), 'type_id'],
                [sequelize.col('type.name'), 'type_name']
            ],
            include: [
                {
                    model: app.model.ModType,
                    as: 'type',
                    // 指定关联表查询属性，这里表示不需要任何关联表的属性
                    attributes: [],
                    // through: {
                    //     // 指定中间表的属性，这里表示不需要任何中间表的属性
                    //     attributes: [['project.projectName', 'projectName']],
                    // }
                },
            ],

            raw: true,
            // 这个需要和上面的中间表属性配合，表示不忽略include属性中的attributes参数
            includeIgnoreAttributes: true,
        });
        return data;
    }
    async findOne(id) {
        const { ctx } = this;
        const data = await ctx.model.ModCommodity.findOne({ where: { status: 1, id }, })
        return data
    }
    // ------------------------------ create
    async create(body: any) {
        const { ctx } = this;
        // const type = await ctx.model.ModCommodity.findOne({ where: { name: body.name, status: 1 } });
        // if (type) {
        //     return ctx.throw('该商品已存在', 201);
        // }
        await ctx.model.ModCommodity.create(body);
        return {};
    }
    // ------------------------------ updata
    async updata(id: any, body: any) {
        const { ctx } = this;
        const type = await ctx.model.ModCommodity.findOne({ where: { id } });

        if (type) {
            const data = await type.update(body);
            return data;
        } else {
            return ctx.throw('无此ID', 201);
        }
    }
    // ------------------------------ del
    async del(id: any) {
        const { ctx } = this;
        const type = await ctx.model.ModCommodity.findOne({ where: { id } });

        if (type) {
            await type.update({ ...type, status: 0 });
            return {};
        } else {
            return ctx.throw('无此ID', 201);
        }
    }
}
